const globby = require('globby')
const path = require('path')
const fs = require('fs')

const cwd = path.resolve(process.cwd(), '../')
const paths = globby.sync(['src/**/*.{vue,jsx}'], { cwd })
const componentName = 'LoadingView'
const componentPath = `import ${componentName} from '@/components/${componentName}'`

// const componentReg = new RegExp(`(?!=components: \\{[\\s\\S]*?)([\\s]*?\\b${componentName}\\b,?)(?=[\\w\\s,]*?})`, 'gm')
const componentReg = new RegExp(
  `(?!components: \\{[\\s\\S]*?)((\\s+^[\\s]*?)*?\\s?${componentName},?)(?=[\\s\\w:,\\()=>/@'\\.]*?})`,
  'gm'
)
// (?!components: \{[\s\S]*?)(ResizeObserver,*?)(?=[\s\w:,\()=>/@'\.]*?})
// (?!components: \{[\s\S]*?)((\s+^[\s]*?)*?EmptyView,?+)(?=[\s\w:,\()=>/@'\.]*?})
const importReg = new RegExp(`\\s+^[\\s]*?${componentPath}`, 'gm')

for (let i = 0; i < paths.length; i++) {
  let fileContent = fs.readFileSync(path.resolve(cwd, paths[i]), { encoding: 'utf8' })
  const hit = componentReg.test(fileContent) || importReg.test(fileContent)
  if (hit) {
    fileContent = fileContent.replace(componentReg, '')
    fileContent = fileContent.replace(importReg, '')
    fs.writeFileSync(path.resolve(cwd, paths[i]), fileContent, { encoding: 'utf8' })
  }
}
